import React from 'react';
import {
    Button,
    Text,
    View,
    Image,
    StyleSheet,
    Dimensions,
    StatusBar,
    ActivityIndicator,
    FlatList,
    ScrollView,
    RefreshControl,
    Animated,
    TouchableHighlight,
    SectionList,
    TouchableOpacity,
    Modal, DeviceEventEmitter
} from 'react-native';
import Swiper from 'react-native-swiper';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import AsyncStorage from '@react-native-community/async-storage';
const { width, height } = Dimensions.get('window');
import Styles from './Styles';

import app from '../../../app.json';
import Ugame from '../../../Ugame';
import Httpc from "../../utils/Httpc";
import REQUEST from "../../../REQUEST";
import Football from "../../utils/Football";
import Utils from "../../utils/Utils";

import RootSiblings from 'react-native-root-siblings';
import { Card } from 'react-native-shadow-cards';

//引入
import ScrollableTabView, { DefaultTabBar, ScrollableTabBar } from 'react-native-scrollable-tab-view';
import CateLists from './CateLists';


var id = 0;
var elements = [];


export default class FollowList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            single_type: {},
            curr_single_type: { id: 0, data: '全部跟单' },

            loaded: false,
            refreshing: false,
            tabShow: false,
            types: [
                { id: 1, gid: 0, label: '命中最高', isshow: true, img: require('../../image/js_img_icon_followorderbuyshop_mz.png'), data: [] },
                { id: 2, gid: 0, label: '利益最高', isshow: false, img: require('../../image/js_img_icon_followorderbuyshop_mz.png'), data: [] },
                { id: 3, gid: 0, label: '带红最多', isshow: true, img: require('../../image/js_img_icon_followorderbuyshop_dh.png'), data: [] },
                { id: 4, gid: 0, label: '我的关注', isshow: true, img: require('../../image/js_img_icon_followorderbuyshop_dh.png'), data: [] }
            ],

        };
        this.getServerData = this.getServerData.bind(this);

    }
    static navigationOptions = ({ navigation }) => {
        const { params } = navigation.state;
        let curr_single_type_data = navigation.getParam('curr_single_type_data');
        return {
            headerTitle: () => (
                <View style={Styles.header}>
                    <View></View>
                    <TouchableOpacity onPress={navigation.getParam('show_single_type')}>
                        <View style={Styles.header_title}>
                            <Text style={{ color: '#ffffff' }}>{curr_single_type_data}</Text>
                            <Image resizeMode="cover" style={{ width: 12, height: 14 }} source={require('../../image/js_img_nav_arrows.png')} />
                        </View>
                    </TouchableOpacity>
                    <View style={Styles.header_right}>

                    </View>
                </View>
            ),
            headerStyle: {
                backgroundColor: '#d0162e',
            paddingTop: 18,
            },
            headerTintColor: '#fff',
            headerTitleStyle: {
                //fontWeight: 'bold',
            },
        };
    };
    componentWillMount() {
        //组件将要被加载到视图之前调用
        this.setState({
            isLogin: Ugame.isLogin()
        });
    }
    componentDidMount() {
        const { navigation } = this.props;
        let curr_single_type = this.state.curr_single_type;
        this.props.navigation.setParams({ curr_single_type_data: curr_single_type.data });
        this.props.navigation.setParams({ show_single_type: this.show_single_type });
        let single_type = this.state.single_type;
        single_type[0] = '全部跟单';
        for (let key in Ugame.gmlist) {
            single_type[key] = Ugame.gmlist[key].Name
        }
        setTimeout(() => {
            this.setState({
                tabShow: true,
                single_type: single_type
            }, () => {
                this.getServerData(() => {
                });
            });
            if (!Ugame.isLogin()) {
                this.props.navigation.navigate('Login');
            }
        }, 0)

    }
    componentWillUnmount() {
        if (elements.length > 0) {
            this.destroySibling();
        }
    }
    show_single_type = () => {
        if (elements.length == 0) {
            let sibling = new RootSiblings(this._show_single_type_model());
            id++;
            elements.push(sibling);
        } else {
            this.destroySibling();
        }
    };
    _show_single_type_model = () => {
        let { single_type, curr_single_type } = this.state;
        return (
            <TouchableOpacity style={Styles.sibling} onPress={this.destroySibling}>
                <View style={Styles.cate_menu}>
                    <View style={Styles.cate_list}>
                        {this.renderSingleType()}
                    </View>
                </View>
            </TouchableOpacity >
        );
    }
    destroySibling = () => {
        let lastSibling = elements.pop();
        lastSibling && lastSibling.destroy();
    };
    renderSingleType() {
        let { single_type, curr_single_type } = this.state;
        var itemArr = [];
        for (let key in single_type) {
            let data = single_type[key];
            itemArr.push(
                <TouchableOpacity key={key} onPress={() => this.change_single_type(key, data)}>
                    <View >
                        <Text style={data == curr_single_type.data ? Styles.cate_item_on : Styles.cate_item}>{data}</Text>
                    </View>
                </TouchableOpacity>
            );
        }
        return itemArr;
    }
    change_single_type = (key, data) => {
        this.props.navigation.setParams({ curr_single_type_data: data });
        this.destroySibling();
        this.setState({
            curr_single_type: {
                id: key,
                data: data
            }
        }, () => {
            //过滤数据
            DeviceEventEmitter.emit('updateCateLists',{gid:key});
            //end
        });
    }

    getServerData = () => {
        let types = this.state.types;
        for (let i = 0; i < types.length; i++) {
            if (!types[i].isshow) {
                continue;
            }
            let params = {};
            params.rootid = app.rootid;
            params.type = types[i].id;
            params.days = 30;
            params.page = 1;
            params.rows = 3;
            Httpc.get(REQUEST.GetFollowRank, params, (res) => {
                if (res.StatusCode == 1) {
                    types[i].data = res.Data;
                }
                if(i==types.length-1){
                    this.setState({
                        types: types
                    })
                }
            });
        }
 

    }
    _on_GetUserGodsDetail = (user) => {
        if (Ugame.isLogin()) {
            this.props.navigation.navigate('UserDetailed', {
                user: user
            });
        } else {
            this.props.navigation.navigate('Login');
        }
    }
    _on_rank = () => {
        if (Ugame.isLogin()) {
            this.props.navigation.navigate('UserRank', {
                days: 7
            });
        } else {
            this.props.navigation.navigate('Login');
        }
    }
    renderSwiper() {
        var itemArr = [];
        let types = this.state.types;
        for (let i = 0; i < 3; i++) {
            if (!types[i].isshow) {
                continue;
            }
            if (!!types[i].data[0]) {
                if (!!types[i].data[0].head) {
                    types[i].data[0].head_img = { uri: 'data:image/png;base64,' + types[i].data[0].head };
                } else {
                    types[i].data[0].head_img = require('../../image/js_img_user_head.png');
                }                
            }
            if (!!types[i].data[1]) {
                if (!!types[i].data[1].head) {
                    types[i].data[1].head_img = { uri: 'data:image/png;base64,' + types[i].data[1].head };
                } else {
                    types[i].data[1].head_img = require('../../image/js_img_user_head.png');
                }                
            }
            if (!!types[i].data[2]) {
                if (!!types[i].data[2].head) {
                    types[i].data[2].head_img = { uri: 'data:image/png;base64,' + types[i].data[2].head };
                } else {
                    types[i].data[2].head_img = require('../../image/js_img_user_head.png');
                }                
            }
            var myreg = /^[1][0-9][0-9]{9}$/;

            itemArr.push(
                <Card key={Number(i) + 1} style={{ width: width - 12, height: 168, backgroundColor: '#ffffff', borderRadius: 5, margin: 6 }}>
                    <View key={Number(i) + 1} style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', width: width - 24, height: 30, padding: 16 }}>
                        <View style={{width: (width - 56) / 3 }}></View>
                        <Image resizeMode="cover" source={types[i].img} />
                        <TouchableOpacity style={{width: (width - 56) / 3, flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center' }} onPress={() => this._on_rank()}>
                            <Text style={{ color: '#5e94c1', fontSize: 12 }}>全部 ></Text>
                        </TouchableOpacity>

                    </View>
                    <View style={{ flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center' }}>
                        {!!types[i].data[1] ?
                            <TouchableOpacity onPress={() => this._on_GetUserGodsDetail(types[i].data[1])}>
                                <View style={{ flexDirection: 'column', justifyContent: 'center', alignItems: 'center', marginTop: 20, width: (width - 24) / 3 }}>
                                    <Image resizeMode="cover" style={{ top: 10, left: -15 }} source={require('../../image/js_img_rank_followorder_two.png')} />
                                    <Image resizeMode="cover" style={{ width: 40, height: 40, borderRadius: 40, borderColor: '#d8d8d8', borderWidth: 2 }} source={types[i].data[1].head_img} />
                                    <Text style={{ color: '#333333' }}>
                                        {myreg.test(types[i].data[1].nick) ? Utils.plusXing(types[i].data[1].nick, 3, 6) : types[i].data[1].nick}
                                    </Text>
                                    {types[i].id != 3 ?
                                        <Text style={{ color: '#d0162e' }}>{types[i].data[1].mark}%</Text> :
                                        <Text style={{ color: '#d0162e' }}>{types[i].data[1].mark}人</Text>
                                    }
                                </View>
                            </TouchableOpacity> :
                            null
                        }
                        {!!types[i].data[0] ?
                            <TouchableOpacity onPress={() => this._on_GetUserGodsDetail(types[i].data[0])}>
                                <View style={{ flexDirection: 'column', justifyContent: 'center', alignItems: 'center', width: (width - 24) / 3 }}>
                                    <Image resizeMode="cover" style={{ top: 12, left: -20 }} source={require('../../image/js_img_rank_followorder_one.png')} />
                                    <Image resizeMode="cover" style={{ width: 58, height: 58, borderRadius: 58, borderColor: '#f6ce07', borderWidth: 2 }} source={types[i].data[0].head_img} />
                                    <Text style={{ color: '#333333' }}>
                                        {myreg.test(types[i].data[0].nick) ? Utils.plusXing(types[i].data[0].nick, 3, 6) : types[i].data[0].nick}
                                    </Text>
                                    {types[i].id != 3 ?
                                        <Text style={{ color: '#d0162e' }}>{types[i].data[0].mark}%</Text> :
                                        <Text style={{ color: '#d0162e' }}>{types[i].data[0].mark}人</Text>
                                    }
                                </View>
                            </TouchableOpacity> :
                            null
                        }
                        {!!types[i].data[2] ?
                            <TouchableOpacity onPress={() => this._on_GetUserGodsDetail(types[i].data[2])}>
                                <View style={{ flexDirection: 'column', justifyContent: 'center', alignItems: 'center', marginTop: 20, width: (width - 24) / 3 }}>
                                    <Image resizeMode="cover" style={{ top: 10, left: -15 }} source={require('../../image/js_img_rank_followorder_three.png')} />
                                    <Image resizeMode="cover" style={{ width: 40, height: 40, borderRadius: 40, borderColor: '#88683c', borderWidth: 2 }} source={types[i].data[2].head_img} />
                                    <Text style={{ color: '#333333' }}>
                                        {myreg.test(types[i].data[2].nick) ? Utils.plusXing(types[i].data[2].nick, 3, 6) : types[i].data[2].nick}
                                    </Text>
                                    {types[i].id != 3 ?
                                        <Text style={{ color: '#d0162e' }}>{types[i].data[2].mark}%</Text> :
                                        <Text style={{ color: '#d0162e' }}>{types[i].data[2].mark}人</Text>
                                    }
                                </View>
                            </TouchableOpacity> :
                            null
                        }

                    </View>
                </Card>
            );
        }
        return itemArr;
    }
    // 滑动tab
    renderScrollableTab = () => {
        let { types, curr_single_type } = this.state;
        if (this.state.tabShow) {
            return (
                <ScrollableTabView
                    style={{ paddingTop: 8 }}
                    renderTabBar={() =>
                        <ScrollableTabBar
                            style={{ height: 35 }}
                            tabStyle={{ height: 35 }}
                        />
                    }
                    tabBarBackgroundColor='#fff'
                    tabBarActiveTextColor='#333333'
                    tabBarInactiveTextColor='#bbbbbb'
                    tabBarUnderlineStyle={Styles.tabBarUnderlines}
                >
                    {
                        types.map((item, index) => {
                            if (item.isshow) {
                                return <CateLists navigation={this.props.navigation} tabLabel={item.label} gid={curr_single_type.id} days={7} key={++index} type={item.id} />;
                            }
                        })
                    }

                </ScrollableTabView>
            )
        }
    }
    render() {
        let { ball_addr, select_boll_addr, dataSource, bet_count } = this.state;
        return (
            <View style={Styles.container}>
                <StatusBar translucent={true} backgroundColor="transparent" />
                <View style={{ backgroundColor: '#d0162e', width: width, height: 160, marginTop: -100, position: "absolute", top: 0 }}></View>
                <View style={{ height: 190 }}>
                    <Swiper
                        style={Styles.wrapper}
                        showsButtons={false} // 分页风格
                        paginationStyle={Styles.paginationStyle}
                        // 点样式
                        dotStyle={Styles.dotStyle}
                        // 活动点样式
                        activeDotStyle={Styles.activeDotStyle}
                    >
                        {this.renderSwiper()}
                    </Swiper>
                </View>
                {this.renderScrollableTab()}


            </View>
        )
    }
}

